// 静态属性，样式属性，剥离数据 多种屏幕尺寸都事先部署好
import echarts from 'echarts'
const staticOption = {
  color: ['#4ca6ff'],
  tooltip: {
    trigger: 'item'
  },
  grid: {
    left: '8%',
    right: '8%',
    bottom: '30%',
    top: '25%',
    containLabel: true
  },
  yAxis: [
    {
      type: 'category',
      offset: 10,
      boundaryGap: false,
      data: [],
      axisLabel: {
        fontSize: 36,
        color: '#cccccc',
        interval: 0
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      }
    }
  ],
  xAxis: [
    {
      type: 'value',
      axisLabel: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '',
      type: 'bar',
      smooth: true,
      label: {
        show: true,
        position: 'right',
        textStyle: {
          fontSize: 36
        }
      },
      itemStyle: {
        barBorderRadius: 12
      },
      barMaxWidth: 24,
      data: []
    }
  ]
}

// 备选颜色，有需求则进行循环
const colors = ['#007bff', '#8ae267', '#ffcf6a']
const gradientColors = [
  (new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
    // 0% 处的颜色
    offset: 0,
    color: '#007bff'
  }, {
    // 100% 处的颜色
    offset: 1,
    color: '#00afff'
  }
  ], false)), (new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
    // 0% 处的颜色
    offset: 0,
    color: '#8ae267'
  }, {
    // 100% 处的颜色
    offset: 1,
    color: '#baf0a0'
  }
  ], false)), (new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
    // 0% 处的颜色
    offset: 0,
    color: '#ffcf6a'
  }, {
    // 100% 处的颜色
    offset: 1,
    color: '#ffe5a1'
  }
  ], false))]
let colorIndex = 0

// 获取设备宽度
// const screen = window.screen.width

class ChartFactory {
  constructor (additionalOptions) {
    // 根据屏幕宽度获取不同配置的echarts配置
    this.option = staticOption
    // 下方复制属于浅拷贝，指向同个内存，针对可能有更改的需求，要进行一次清理
    this.clear()
    // 装配数据 必须使用箭头函数
    colorIndex = 0
    let xMax = 0
    additionalOptions.seriesData.forEach((p1) => {
      if (p1.value > xMax) {
        xMax = p1.value
      }
      this.option.series[0].data.push({
        name: p1.name,
        value: p1.value,
        itemStyle: {
          color: gradientColors[colorIndex]
        },
        label: {
          color: colors[colorIndex],
          formatter: function (params) {
            return params.value.toLocaleString()
          }
        }
      })
      this.option.yAxis[0].data.push(p1.name)
      // 调整Y轴的值
      this.option.xAxis[0].max = xMax * 1.4
      colorIndex += 1
    })
  }

  // 清理方法，要将部署的新数据全部置空
  clear () {
    this.option.series[0].data = []
    this.option.yAxis[0].data = []
  }

  getOption () {
    return this.option
  }
}

export { ChartFactory }
